<?php

namespace App\Console\Commands\OpenShop;

use App\Library\Rms\RmsUserApi;
use App\Models\Common\AmapAreaModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Remote\Rms\RmsUserRemote;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class RefreshProvinceDevelopers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:refresh-province-developers';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新省区开发人员信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        //$this->doHandle();

        // 获取用户省区列表
        $usersInfo = $this->getDevelopmentUserList();

        $this->addDevelopment($usersInfo);
    }


    public function addDevelopment($usersInfo)
    {
        // 获得分公司的ID于省区的Code
        $mappings = OpenShopOrganizationRegionMappingModel::query()
            ->pluck('manageId', 'provinceCode')
            ->toArray();

        DB::beginTransaction();

        foreach ($usersInfo as $userInfo) {

            // 先删除
            OpenShopOrganizationManageUserModel::query()
                ->where('userId', $userInfo['userId'])
                ->where('type', OpenShopOrganizationManageUserModel::TYPE_PROVINCE_DEVELOP)
                ->update(['isDeleted' => 1]);

            // 添加
            foreach ($userInfo['provinceCodes'] as $item) {
                if (!isset($mappings[$item])) {
                    continue;
                }
                dump($userInfo['username']);

                OpenShopOrganizationManageUserModel::query()->withoutGlobalScope('isDel')->updateOrCreate([
                    'userId'   => $userInfo['userId'],
                    'type'     => OpenShopOrganizationManageUserModel::TYPE_PROVINCE_DEVELOP,
                    'manageId' => $mappings[$item],
                ], [
                    'name'      => $userInfo['username'],
                    'isDeleted' => 0,
                ]);
            }
        }
        DB::commit();
    }



    public function getDevelopmentUserList(): array
    {
        // 匹配所有未离职的省区开发
        return KmsUser::query()
            ->where('rootDepartmentName', '分公司')
            ->where('isFrozen', 0)
            ->where('isResigned', KmsUser::IS_RESIGNED_OFF)
            ->where('isExited', KmsUser::IS_EXITED_OFF)
            ->where('departmentName', 'like', '%办公室')
            ->get()
            ->map(function (KmsUser $kmsUser) {
                return [
                    'userId'        => $kmsUser->rmsUserId,
                    'username'      => $kmsUser->nickname . '(' . $kmsUser->name . ')',
                    'province'      => $province = str_replace('办公室', '', $kmsUser->departmentName),
                    'provinceCodes' => $this->getProvinceCodes($province)
                ];
            })->toArray();
    }


    /**
     * 获取省区code
     * @param $province
     * @return int[]
     */
    public function getProvinceCodes($province): array
    {
        // 特殊情况
        if ($province == '西北') {
            return [
                140000, // 山西
                610000, // 陕西
                620000, // 甘肃
                640000, // 宁夏
                650000, // 新疆
            ];
        }

        if ($province == '西南') {
            return [
                510000, // 四川
                500000, // 重庆
                520000, // 贵州
                530000, // 云南
                540000, // 西藏
            ];
        }

        if ($province == '东北') {
            return [
                210000, // 辽宁
                220000, // 黑龙江
                230000, // 吉林
            ];
        }

        $provinceCode = (int)AmapAreaModel::query()
            ->where('level', AmapAreaModel::LEVEL_PROVINCE)
            ->where('label', 'like', $province . '%')
            ->value('code');

        return [$provinceCode];
    }



    public function doHandle(array $rmsUserIds = [])
    {
        $fsLists = collect((new RmsUserApi())->getFsUsers('办公室')['data']['lists'] ?? [])->map(function ($item) {
            $item['provinceAreaPrefix'] = mb_substr($item['departmentName'], 0, 3);
            $item['provinceAreaPrefix'] = rtrim($item['provinceAreaPrefix'], '办');
            return $item;
        })->when($rmsUserIds, function ($query) use ($rmsUserIds) {
            return $query->whereIn('rmsUserId', $rmsUserIds);
        });

        if (!$fsLists->count()) {
            dump("不存在的用户");
            return;
        }

        $fsLists = $fsLists->keyBy('mobile');

        $mobiles = $fsLists->pluck('mobile')->toArray();

        // 批量转换成userId
        $userLists = collect((new RmsUserApi())->getUserInfoByMobiles($mobiles)['data'] ?? [])->keyBy('id');
        $userIds   = $userLists->pluck('id')->toArray();

        // 获取职位
        $roleId = (new RmsUserApi())->roleIdsConfig()['data']['role']['province_develop_id'];

        $okUserIds = [];

        foreach ($userIds as $userId) {
            $isRoleUser = RmsUserRemote::isRoleUser($roleId, $userId)['isRoleUser'] ?? false;

            if ($isRoleUser) {
                $okUserIds[] = $userId;
            }
        }

        DB::beginTransaction();

        // 先删除
        OpenShopOrganizationManageUserModel::query()
                                           ->when($rmsUserIds, function ($query) use ($rmsUserIds) {
                                               $query->whereIn('userId', $rmsUserIds);
                                           })
                                           ->where('type', OpenShopOrganizationManageUserModel::TYPE_PROVINCE_DEVELOP)
                                           ->update(['isDeleted' => 1]);

        foreach ($okUserIds as $userId) {

            $mobile             = $userLists[$userId]['mobile'] ?? '';
            $provinceAreaPrefix = $fsLists[$mobile]['provinceAreaPrefix'] ?? '';
            if (!$provinceAreaPrefix) {
                continue;
            }

            $manageId = OpenShopOrganizationManageModel::query()
                                                       ->where('name', 'like', "%{$provinceAreaPrefix}%")
                                                       ->value('id') ?? 0;
            if (!$manageId) {
                continue;
            }

            // 入库
            $s = OpenShopOrganizationManageUserModel::query()->withoutGlobalScope('isDel')->updateOrCreate([
                'userId'   => $userId,
                'type'     => OpenShopOrganizationManageUserModel::TYPE_PROVINCE_DEVELOP,
                'manageId' => $manageId,
            ], [
                'name'      => $userLists[$userId]['username'] ?? '',
                'isDeleted' => 0,
            ]);

            if ($rmsUserIds) {
                dump($s->name);
            }
        }

        DB::commit();
    }
}
